import { relaunch } from '@tauri-apps/plugin-process';
import { check } from '@tauri-apps/plugin-updater';
import { onMounted, ref } from 'vue';

export function useUpdater() {
  const updateAvailable = ref(false);
  let totalLength = ref(0);
  let downloadedLength = ref(0);
  let currentVersion = ref('');
  let newVersion = ref('');
  let errorMessage = ref('');

  onMounted(checkUpdate);

  async function checkUpdate(): Promise<void> {
    const update = await check();

    if (update?.rid != null) {
      updateAvailable.value = true;
      currentVersion.value = update.currentVersion;
      newVersion.value = update.version;

      try {
        // alternatively we could also call update.download() and update.install() separately
        await update.downloadAndInstall((event) => {
          switch (event.event) {
            case 'Started':
              totalLength.value = event.data.contentLength!;
              break;
            case 'Progress':
              downloadedLength.value += event.data.chunkLength;
              break;
            case 'Finished':
              break;
          }
        });

        await relaunch();
      } catch (ex: any) {
        errorMessage.value = ex.toString();
      }
    }
  }

  return {
    updateAvailable,
    currentVersion,
    newVersion,
    totalLength,
    downloadedLength,
    errorMessage,
  };
}
